<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Install\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Install\Command\UpgradeCommand;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\Tenant\Contract\TenantMenuPackageContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Logic\FieldPivot\UpdatePhoneLogic;
use MoChat\Plugin\TenantProduct\Contract\TenantProductContract;
use MoChat\Plugin\TenantProduct\Contract\TenantProductSkuContract;
use Psr\Container\ContainerInterface;

/**
 * 版本升级逻辑 1.5.0.
 */
class Upgrade1D5D0Logic
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var TenantMenuPackageContract
     */
    protected $tenantMenuPackageService;

    /**
     * @var TenantProductContract
     */
    protected $tenantProductService;

    /**
     * @var TenantProductSkuContract
     */
    protected $tenantProductSkuService;

    /**
     * @var TenantContract
     */
    protected $tenantService;

    /**
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * 更新客户画像-手机号.
     * @var UpdatePhoneLogic
     */
    protected $updatePhoneLogic;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var UpgradeCommand
     */
    private $command;

    /**
     * @var CorpContract
     */
    private $corpService;

    /**
     * Upgrade1D4D2Logic constructor.
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function __invoke(UpgradeCommand $command)
    {
        $this->command = $command;
        try {
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->tenantMenuPackageService = $this->container->get(TenantMenuPackageContract::class);
            $this->tenantProductService = $this->container->get(TenantProductContract::class);
            $this->tenantProductSkuService = $this->container->get(TenantProductSkuContract::class);
            $this->tenantService = $this->container->get(TenantContract::class);
            $this->corpService = $this->container->get(CorpContract::class);
            $this->workContactEmployeeService = $this->container->get(WorkContactEmployeeContract::class);
            $this->updatePhoneLogic = $this->container->get(UpdatePhoneLogic::class);

            // 查询所有套餐
            $skus = $this->tenantProductSkuService->getTenantProductSkus();
            if (! empty($skus)) {
                // 创建套餐-套餐功能属性关联
                foreach ($skus as $item) {
                    $this->handleSkuData($item);
                }
            }

            // 查询所有企业
            $corps = $this->corpService->getCorps();
            if (empty($corps)) {
                return;
            }
            foreach ($corps as $item) {
                $this->handleCorpData($item['id']);
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('1.4.0升级数据处理失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }

    /**
     * 处理租户套餐.
     */
    private function handleSkuData(array $sku): void
    {
        // 查询套餐-套餐功能属性
        $attributes = $this->tenantProductSkuService->getTenantProductSkuValuesById(explode(',', $sku['attributes']));
        // 创建套餐-套餐功能属性关联
        foreach ($attributes as $item) {
            if ($item['attributeName'] === '套餐功能') {
                $data = [
                    'sku_id' => $sku['id'],
                    'menu_id' => $item['attributeValue'],
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                if (empty($this->tenantMenuPackageService->getTenantMenuPackageBySkuId($sku['id']))) {
                    $menuPackageId = $this->tenantMenuPackageService->createTenantMenuPackage($data);
                    $tenants = $this->tenantService->getTenantBySkuId($sku['id'], ['id']);
                    // 更新租户-套餐功能属性关联
                    if (! empty($tenants)) {
                        $tenantIds = array_column($tenants, 'id');
                        $this->tenantService->updateTenantsById($tenantIds, ['menu_package_id' => $menuPackageId]);
                    }
                }
                break;
            }
        }
    }

    /**
     * 客户画像中的phone和remark_mobiles合并原始数据处理.
     */
    private function handleCorpData(int $corpId)
    {
        $contactEmployee = $this->workContactEmployeeService->getWorkContactEmployeesByCorpId($corpId, ['employee_id', 'contact_id', 'remark_mobiles']);
        foreach ($contactEmployee as $val) {
            // 更新客户画像-手机号
            $phoneData = ['contactId' => $val['contactId'], 'employeeId' => $val['employeeId'], 'remarkMobiles' => Json::decode($val['remarkMobiles'])];
            $this->updatePhoneLogic->handle($phoneData);
        }
    }
}
